package org.uek.ships.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uek.shpis.common.transport.Command;

public class GameThread implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(GameThread.class);

	private PlayerPair playerPair;

	private ObjectInputStream firstPlayerObjectInputStream;

	private ObjectInputStream secondPlayerObjectInputStream;

	private ObjectOutputStream firstPlayerObjectOutputStream;

	private ObjectOutputStream secondPlayerObjectOutputStream;

	public GameThread(PlayerPair playerPair) throws IOException {
		super();
		this.playerPair = playerPair;

		firstPlayerObjectOutputStream = new ObjectOutputStream(playerPair.getFirstPlayerSocket().getOutputStream());
		secondPlayerObjectOutputStream = new ObjectOutputStream(playerPair.getSecondPlayerSocket().getOutputStream());
		
		firstPlayerObjectInputStream = new ObjectInputStream(playerPair.getFirstPlayerSocket().getInputStream());
		secondPlayerObjectInputStream = new ObjectInputStream(playerPair.getSecondPlayerSocket().getInputStream());
		
	}

	@Override
	public void run() {

		logger.debug("START, players : " + playerPair);

		Scanner scanner;
		try {
			scanner = new Scanner(playerPair.getFirstPlayerSocket().getInputStream());

			PrintWriter firstPlayerWritter = new PrintWriter(playerPair.getSecondPlayerSocket().getOutputStream(), true);
			PrintWriter secondPlayerWritter = new PrintWriter(playerPair.getSecondPlayerSocket().getOutputStream(), true);

			firstPlayerObjectOutputStream.writeObject(new Command("Play"));
			secondPlayerObjectOutputStream.writeObject(new Command("Play"));

			while (true) {
				Command command = (Command) firstPlayerObjectInputStream.readObject();

				if (command != null) {
					logger.info("Otrzymałem komende FP : " + command.getMessage());
				}

				command = (Command) secondPlayerObjectInputStream.readObject();

				if (command != null) {
					logger.info("Otrzymałem komende SP: " + command.getMessage());
				}

			}

		} catch (Exception e) {
			logger.error("Exception in game thread", e);
		}

	}

}
